
package com.trippin.servlets;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.trippin.DB.DBHandler;
import com.trippin.DB.entities.AttractionEntity.ShortDetailedAttraction;
import com.trippin.Utils.ServletUtil;
import com.trippin.Utils.ServletUtilConstants;


@SuppressWarnings("serial")
public class LocationServlet extends HttpServlet {

	private static final Logger logger = Logger.getLogger(LocationServlet.class.getCanonicalName());

	private static DBHandler dbHandlerInstance = DBHandler.INSTANCE;

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		resp.setContentType("application/json");

		Action action = ServletUtil.getActionFromHeader(req,resp,LocationServlet.class.toString());
		long userId  = ServletUtil.getLongFromHeader(req, resp, ServletUtilConstants.USER_ID,
				LocationServlet.class.toString(),action.getName());

		try {	
			String bodyResponse = "";	
			switch(action) {
			case GET_LOCATION_ATTRACTIONS:
				// TODO handle paging!!!! (in all servlets).
				bodyResponse = getLocationAttractions(userId,req,resp,action.getName());
				break;
			default:
				ServletUtil.printError(resp, action.getName(),LocationServlet.class.getName(), 
						ServletUtilConstants.ERROR_WRONG_ACTION_NAME);	
				return;
			}

			ServletUtil.createResponse(resp, action.getName(), bodyResponse);

		}  catch(Exception e) {
			ServletUtil.printError(resp,action.getName(), LocationServlet.class.getName(), e.getMessage());
			logger.log(Level.SEVERE,e.toString(), e);
		}

	}

	private String getLocationAttractions(long userId, HttpServletRequest req, HttpServletResponse resp, String actionName) 
			throws ServletException, IOException  {
		double latN = 0, latS = 0, lonE = 0, lonW = 0;
		try {
			latN = Double.parseDouble(req.getHeader(ServletUtilConstants.COORDINATES_LAT_N));
			latS = Double.parseDouble(req.getHeader(ServletUtilConstants.COORDINATES_LAT_S));
			lonE = Double.parseDouble(req.getHeader(ServletUtilConstants.COORDINATES_LON_E));
			lonW = Double.parseDouble(req.getHeader(ServletUtilConstants.COORDINATES_LON_W));
		} catch(Exception e){
			ServletUtil.printError(resp,actionName,LocationServlet.class.getName(), ServletUtilConstants.ERROR_MISSING_COORDINATES);
		}

		Date startTime = ServletUtil.getDateTime(req,ServletUtilConstants.START_TIME);
		Date endTime = ServletUtil.getDateTime(req,ServletUtilConstants.END_TIME);

		Iterable<ShortDetailedAttraction> shortaAttractions = 
				dbHandlerInstance.getAttractions(userId, latN, lonE, latS, lonW,startTime, endTime);
		return ServletUtil.getResponseBody(shortaAttractions);
	}

}

